﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using DevComponents.AdvTree;
using DevComponents.DotNetBar;

namespace PolePosition.v3.Desktop.Grids
{
    public partial class GridXMissionGPSToAsset : GridVisitToAssetBase
    {
        public GridXMissionGPSToAsset() : base(Common.Enumerations.DataTypes.ProjectsXmissionGpsVisit)
        {
            InitializeComponent();
        }


        public override void DoVisitToAsset()
        {
            try
            {
                CheckAssetsIds();
            }
            catch (Exception exc)
            {
                MessageBoxEx.Show(exc.Message, "PPI", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                var xml = GetSourceAsXML();
                ServiceProxy.UtilityService.CreateXMissionAssetsFromVisits(DataKeyId, XElement.Parse(xml.InnerXml));
                MessageBoxEx.Show("Assets were created/updated succesfully!", "PPI", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exc)
            {
                MessageBoxEx.Show(exc.Message, "PPI", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                DoRefresh();
            }
        }
        private void advTreeInspectionVisitsToAssets_AfterCellEditComplete(object sender, CellEditEventArgs e)
        {
            e.Cell.Text = e.Cell.Text.Trim();

            if (e.Cell.Text.Equals(string.Empty))
                e.Cell.Text = newText;

            if (!e.Cell.Text.Equals(newText))
            {
                int valueTyped;
                if (!int.TryParse(e.Cell.Text, out valueTyped))
                {
                    MessageBoxEx.Show("Value typed is not a number.", "Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    e.Cell.StyleNormal = new ElementStyle { BackColor = Color.White };
                    e.Cell.Text = newText;
                }
            }
        }

        public override void DoAsynchLoad(DoWorkEventArgs e)
        {
            advTreeInspectionVisitsToAssets.Invoke(new MethodInvoker(delegate { advTreeInspectionVisitsToAssets.Enabled = false; }));

            int _TotalRecords;
            e.Result = ServiceProxy.UtilityService.GetXMissionVisitToAssetData(DataKeyId, PageSize, PageNumber, 20, out _TotalRecords);
            TotalItems = _TotalRecords;
        }

        public override void AsychLoadComplete(object sender, RunWorkerCompletedEventArgs e)
        {
            base.AsychLoadComplete(sender, e);
            //do whatever needs to be done after asynch work complete (BackgroudWorker_RunWorkerCompleted)
            if (e.Cancelled)
            {

            }

            if (e.Error != null || e.Result == null)
            {
                //todo: create some sort of error dialog and use it here instead of messagebx
                MessageBoxEx.Show("Error retrieving project data.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            var _data = e.Result as DataTable;

            if (_data == null || _data.Rows.Count == 0)
            {
                if (CurrentSearchType == Common.Enumerations.GridSearchByTpes.None)
                    MessageBoxEx.Show("No data found for the selected asset type.", "No Data Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBoxEx.Show("No data found for the asset type with the applied search.", "No Data Found", MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }

            bindingSourceGridDataParent.DataSource = _data;
            advTreeInspectionVisitsToAssets.DataSource = bindingSourceGridDataParent;
            advTreeInspectionVisitsToAssets.Bind();
            advTreeInspectionVisitsToAssets.Visible = true;
            advTreeInspectionVisitsToAssets.Enabled = true;
        }

        public override void DoAsynchSave(DoWorkEventArgs e)
        {

        }

        public override void AsychSaveComplete(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        public override void DoAsynchGetKml(DoWorkEventArgs e)
        {
            advTreeInspectionVisitsToAssets.Invoke(new MethodInvoker(delegate { advTreeInspectionVisitsToAssets.Enabled = false; }));
        }

        public void GetMetersAssetKML()
        {
        }

        public void GetMeterItemAssetKML()
        {
        }

        public override void AsychGetKmlComplete(object sender, RunWorkerCompletedEventArgs e)
        {
        }


        public void ShowData(int projectId, string projectName)
        {
            DataKeyId = projectId;
            DataDescription = projectName;
            advTreeInspectionVisitsToAssets.Visible = false;
            DataKeyId = projectId;
            StartAsynchLoad();
        }

        private XmlDocument GetSourceAsXML()
        {
            var xmlResult = new XmlDocument();
            xmlResult.LoadXml("<VisitsToAssets />");
            XmlElement _xElementVisitToAsset;
            XmlElement _xElementVisit;
            XmlElement _xElementAsset;

            foreach (Node node in advTreeInspectionVisitsToAssets.Nodes)
            {
                _xElementVisitToAsset = xmlResult.CreateElement("VisitToAsset");
                _xElementVisit = xmlResult.CreateElement("Visit");
                _xElementAsset = xmlResult.CreateElement("Asset");

                _xElementVisit.InnerText = node.Cells[0].Text;
                _xElementAsset.InnerText = !node.Cells[1].Text.Trim().Equals(newText) ? node.Cells[1].Text : string.Empty;

                _xElementVisitToAsset.AppendChild(_xElementVisit);
                _xElementVisitToAsset.AppendChild(_xElementAsset);
                
                if (xmlResult.DocumentElement != null) 
                    xmlResult.DocumentElement.AppendChild(_xElementVisitToAsset);
            }

            return xmlResult;
        }

        private void CheckAssetsIds()
        {
            var nodesToUpdate = new List<int>();
            advTreeInspectionVisitsToAssets.Focus();
            advTreeInspectionVisitsToAssets.SelectedNode = null;

            foreach (Node node in advTreeInspectionVisitsToAssets.Nodes)
            {
                if (!string.IsNullOrEmpty(node.Cells[1].Text) && !node.Cells[1].Text.Equals(newText))
                    nodesToUpdate.Add(int.Parse(node.Cells[1].Text));
            }

            int[] notValidIds = ServiceProxy.UtilityService.XMissionAssetsValidateIds(Program.UserSelections.UtilityId, nodesToUpdate.ToArray());
            var notValidIdsList = new List<int>(notValidIds);
            bool invalidNodes = false;

            foreach (Node node in advTreeInspectionVisitsToAssets.Nodes)
            {
                if (!node.Cells[1].Text.Trim().Equals(newText) && notValidIdsList.Contains(int.Parse(node.Cells[1].Text))) {
                    MarkCellAsInvalid(node.Cells[1]);
                    invalidNodes = true;
                }
            }

            advTreeInspectionVisitsToAssets.Refresh();

            if (invalidNodes)
            {
                advTreeInspectionVisitsToAssets.Focus();
                throw new Exception("Some Ids don't exist.");
            }
        }
    }
}
